<template>
  <div>
    <el-card style="margin:20px 0px">
      <CategorySelect @getCategoryId="getCategoryId" :show="!isShow"/>
    </el-card>
    <el-card>
      <div v-show="isShow">
        <el-button type="primary" icon="el-icon-plus" :disabled="!category3Id" @click="addAttr" @keyup.native.enter="flag=false">添加属性</el-button>
        <!--      表格展示平台属性-->
        <el-table style="width: 100%" border :data="attrList">
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          />
          <el-table-column
            prop="attrName"
            label="属性名称"
            width="150"
          />
          <el-table-column
            prop="prop"
            label="属性值列表"
            width="width"
          >
            <!--          作用域插槽 row就是遍历回来的item-->
            <template slot-scope="{row,$index}">
              <el-tag v-for="(attrValue,index) in row.attrValueList" :key="attrValue.id" type="success" style="margin: 0px 20px">
                {{ attrValue.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="150"
          >
            <template slot-scope="{row,index}">
              <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateAttr(row)" />
              <el-button type="danger" icon="el-icon-delete" size="mini" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--     添加和修改属性点击的结构-->
      <div v-show="!isShow">
        <el-form ref="from" :inline="true" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input v-model="attrInfo.attrName" placeholder="请输入属性名" />
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" :disabled="!attrInfo.attrName" @click="addAttrvalue">添加属性值</el-button>
        <el-button @click="isShow=true">取消</el-button>
        <el-table style="width: 100%;margin: 20px 0px" border :data="attrInfo.attrValueList">
          <el-table-column
            align="center"
            type="index"
            label="序号"
            width="width"
          />
          <el-table-column
            prop="prop"
            label="属性值名称"
            width="width"
          >
            <template slot-scope="{row,$index}">
              <!--              //需要用到span和input时而展示和时而切换-->
              <el-input v-if="row.flag" :ref="$index" v-model="row.valueName" placeholder="请输入属性值名称" size="mini" @blur="toLook(row)" @keyup.native.enter="toLook(row)" />
              <span v-else style="display: block" @click="toEdit(row)">{{ row.valueName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="width"
          >
            <template slot-scope="{row,index}">
              <!--              删除弹框-->
              <el-popconfirm :title="`确定删除${row.valueName}}?`" @confirm="deleteAttrValue(index)">
                <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini" />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="addOrUpdateAttr" :disabled="attrInfo.attrValueList.length < 1">保存</el-button>
        <el-button @click="isShow=true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { reqAttrInfoList } from '@/api/product/attr'
// 按需引入lodash当中的深拷贝
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'Attr',
  data() {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      // 接受平台属性的字段
      attrList: [],
      // 控制表格显示与隐藏
      isShow: true,
      // 收集新增属性，|修改属性
      attrInfo: {
        'attrName': '', // 属性名
        'attrValueList': [ // 属性值
        ],
        'categoryId': 0,
        'categoryLevel': 3
      }
    }
  },
  methods: {
    // 获取品牌数据  const result = await reqAttrInfoList(category1Id, category2Id, category3Id)
    // console.log(result)
    async getAttrList() {
      const { category1Id, category2Id, category3Id } = this
      const result = await reqAttrInfoList(category1Id, category2Id, category3Id)
      if (result.code === 200) {
        this.attrList = result.data
      }
    },
    // 自定义事件的回调，子给父传数据
    getCategoryId({ categoryId, level }) {
      if (level === 1) {
        this.category1Id = categoryId
        this.category2Id = categoryId
        this.category3Id = categoryId
      } else if (level === 2) {
        this.category2Id = categoryId
        this.category3Id = ''
      } else {
        // 代表三级分类的id有了可以发请求获取品牌属性
        this.category3Id = categoryId
        this.getAttrList()
      }
    },
    // 添加属性值的回调
    addAttrvalue() {
      // 向属性值的数组里添加元素
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id,
        valueName: '',
        // 给每一个属性值添加一个标记，用于切换查看模式和编辑模式，每一个属性值都可以控制自己的切换
        flag: true
      })
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus()
      })
    },
    // 添加属性按钮的回调
    addAttr() {
      // 切换显示与隐藏
      this.isShow = false
      // 清空
      this.attrInfo = {
        'attrName': '', // 属性名
        'attrValueList': [ // 属性值
        ],
        'categoryId': this.category3Id,
        'categoryLevel': 3
      }
    },
    // 修改属性。attr
    updateAttr(row) {
      this.isShow = false
      // 将选中的属性等于info
      // 由于数据结构当中存在对象里靠数组，数组里又有对象，则就用深拷贝解决
      this.attrInfo = cloneDeep(row)
      // 在修改某一个属性的时候，将相应的属性值元素添加上flag标记
      this.attrInfo.attrValueList.forEach(item => {
        this.$set(item, 'flag', false)
      })
    },
    // 失去焦点的事件
    toLook(row) {
      // 如果属性值为空不能作为新的属性值，需要给用户提示，让他输入正常属性值
      if (row.valueName.trim() === '') {
        this.$message('请你输入一个正常的属性值')
        return
      }
      // 新增的属性值不能跟已有的属性值
      const isRepat = this.attrInfo.attrValueList.some(item => {
        // 需要把自身去除
        if (row !== item) {
          return row.valueName === item.valueName
        }
      })
      if (isRepat) return
      row.flag = false
    },
    // span点击
    toEdit(row, index) {
      row.flag = true
      // 获取input节点，实现聚焦
      this.$nextTick(() => {
        this.$refs[index].fucos()
      })
    },
    // 气泡确认框确认按钮的回调
    deleteAttrValue(index) {
      this.attrInfo.attrValueList.aplice(index, 1)
    },
    // 保存按钮进行添加属性或者修改属性的操作
    async  addOrUpdateAttr() {
      // 整理参数，如果用户添加了很多属性值，属性值为空不不会提交给服务器
      this.attrInfo.attrValueList.filter(item => {
        // 过滤掉属性值不为空
        if (item.valueName !== '') {
          delete item.falg
          return true
        }
      })
      // 发请求
      try {
        await this.$API.attr.reqAddOrUpdateAttr(this.attrInfo)
        this.isShow = true
        this.getAttrList()
        this.$message({ type: 'cucess', message: '保存成功' })
        // eslint-disable-next-line no-empty
      } catch (error) {

      }
    }
  }

}
</script>

<style scoped>

</style>
